package com.example.net.oss;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.example.baseutils.DateUtils;
import com.example.baseutils.FileUtil;


/**
 * 上传图片到OSS服务器
 */
public class UpFileToOss {
    private static final String TAG = "UpFileToOss";
    private String objectKey;
    private String filePath;
    private static OSS oss = null;
    private Context mContext;

    /**
     *
     */
    public UpFileToOss(Context context) {
        this.mContext = context;
        oss = initOSS();
    }

    /**
     * @param filePath 需要上传的文件路径，包括文件名
     */
    public UpFileToOss(Context context, String filePath, int schoolId) {
        this.mContext = context;
        this.filePath = filePath;
        this.objectKey = getObjectKey(filePath, schoolId);
        Log.i(TAG, "objectKey: "+objectKey);
        oss = initOSS();
    }

    /**
     * 直接根据已经生成好的objectKey完成上传
     */
    public UpFileToOss(Context context, String filePath, String objectKey) {
        this.mContext = context;
        this.filePath = filePath;
        this.objectKey = objectKey;
        oss = initOSS();
    }

    /**
     * 返回的路径是绝对的路径，加了http://imagecdn.didano.com/前缀名
     */
    public String getObjectKey() {
        String absPath = "http://imagecdn.didano.com/" + objectKey;
        return absPath;
    }

    /**
     * 根据上传文件名和学生ID来构造OSS的ObjectKey
     *
     * @param filePath
     * @param schoolId
     * @return
     */
    public static String getObjectKey(String filePath, int schoolId) {
        if (filePath == null) {
            return "";
        }
        String filename = filePath.substring(filePath.lastIndexOf("/") + 1);
        String ossfile = "FantacyPhoto/";
        String objectKey = ossfile + DateUtils.getCurrentShortTime() + "/" + schoolId + "/" + filename;
        Log.i(TAG, "getObjectKey: " +  "http://imagecdn.didano.com/"+objectKey);
        return objectKey;
    }

    /**
     * 执行上传
     * 0，通过
     * -1，本地网络异常
     * -2，服务器异常
     * -3，文件为空
     */
    public Boolean execute(String filePath, String objectKey) {
        //如果地址为空或者不存在文件
        if (filePath == null || !FileUtil.isFileExist(filePath)) {
            return true;
        }

        int ret = uploadAliYunOSSBaseStsServer(objectKey, filePath);
        if (ret == 0) {
            Log.i(TAG, "上传成功 : " + objectKey);
            return true;
        } else if (ret == -2) {
            Log.i(TAG, "上传失败 : " + objectKey);
            return false;
        } else if (ret == -3) {
            Log.e(TAG, "文件为空 : " + objectKey);
            return true;
        }

        return false;

    }

    public int execute() {
        //如果地址为空或者不存在文件
        if (filePath == null || !FileUtil.isFileExist(filePath)) {
            return -3;
        }

        int ret = uploadAliYunOSSBaseStsServer(objectKey, filePath);
//        if (ret == 0) {
//            Log.i(TAG, "上传成功 : " + objectKey);
//            return 0;
//        } else if (ret == -2) {
//            Log.i(TAG, "上传失败 : " + objectKey);
//            return -1;
//        }

        return ret;

    }

    private OSS initOSS() {
        //初始化
        Log.i(TAG, "initOSS..... ");
        String aliyun_oss_url = "/api/service/ossSts";
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        String stsServer = "http://120.77.237.242:8081" + aliyun_oss_url;
        // String stsServer = InvisibleConfigUtil.readString(InvisibleConfigKey.KINDERGARTEN_SERVER_DOMAIN) + InvisibleConfigUtil.readString(InvisibleConfigKey.ALIYUN_OSS_URL);
        //推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);
        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        return new OSSClient(mContext, endpoint, credentialProvider);
    }

    /**
     * 上传至阿里云的OSS服务器
     *
     * @param objectKey 在OSS服务器上的objectKey
     * @param filePath  需要上传的文件路径，包括文件名
     * @return 0表示上传成功， -1表示客户端的网络异常， -2表示服务端异常
     */
    private int uploadAliYunOSSBaseStsServer(String objectKey, String filePath) {
        synchronized (this) {
            if (oss == null) {
                //初始化
                oss = initOSS();
            }
        }

        String bucketName = "image-didanuo";
        // String ossPath = Md5Utils.getMD5(TimeUtil.getYMDHMSDate() + stuID + DeviceUtil.getNumber());
        //String objectKey  = "detection/"+ TimeUtil.getYMDDate() + "/" + DeviceUtil.getNumber() + "_" + stuID + "_" + pic_path.substring(pic_path.lastIndexOf("/") + 1);
        //  String objectKey = "detection/"+ TimeUtil.getYMDDate() + "/" + ossFileName;
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, filePath);
        try {
            PutObjectResult putResult = oss.putObject(put);
            Log.i("PutObject", "UploadSuccess");
            Log.i("ETag", putResult.getETag());
            Log.i("RequestId", putResult.getRequestId());
            Log.e(TAG, "uploadAliYunOSSBaseStsServer: ");
        } catch (ClientException e) {
            Log.i("upBaseStsServer", e.getMessage());
            // 本地异常如网络异常等
            if (e.getMessage().contains("the length of file is 0")) {
                return -3;
            }

            return -1;
        } catch (ServiceException e) {
            // 服务异常
            Log.i("RequestId", e.getRequestId());
            Log.i("ErrorCode", e.getErrorCode());
            Log.i("HostId", e.getHostId());
            Log.i("RawMessage", e.getRawMessage());
            Log.i("ErrorCode", e.getErrorCode());
            Log.i("StatusCode", "status code = " + e.getStatusCode());
            Log.e(TAG, "服务异常 ");
            return -2;
        }

        return 0;
    }


}
